'use client';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Space, Table, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import {
  deleteQuestionBatchUsingPost,
  deleteQuestionUsingPost,
  listQuestionUsingPost,
} from '@/api/QuestionApi';
import TagList from '@/components/TagList';
import MdEditor from '@/components/MdEditer';
import AddBankBatchModal from '@/app/admin/question/components/AddBankBatchModal';
import RemoveBankBatchModal from '@/app/admin/question/components/RemoveBankBatchModal';

/**
 * 题库管理页面
 *
 * @constructor
 */
const QuestionAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  // 是否显示批量新增题目到题库窗口
  const [
    addQuestionToBankBatchModalVisible,
    setAddQuestionToBankBatchModalVisible,
  ] = useState<boolean>(false);
  // 是否显示批量从题库删除题目窗口
  const [
    removeQuestionFromBankBatchModalVisible,
    setRemoveQuestionFromBankBatchModalVisible,
  ] = useState<boolean>(false);

  // 选中题目ID列表
  const [selectQuestionIdList, setSelectQuestionIdList] = useState<number[]>(
    [],
  );

  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.Question>();

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Question) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteQuestionUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef.current.reload();
      return true;
    } catch (e) {
      hide();
      message.error('删除失败，' + e.message);
      return false;
    }
  };

  /**
   * 批量删除题目
   * @param questionIdList
   */
  const handleDeleteBatch = async (questionIdList: number[]) => {
    const hide = message.loading('正在删除...');
    try {
      await deleteQuestionBatchUsingPost({
        questionIdList,
      });
      hide();
      message.success('删除成功');
      return true;
    } catch (e) {
      hide();
      message.error('删除失败，' + e.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Question>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'text',
    },
    {
      title: '内容',
      dataIndex: 'content',
      valueType: 'text',
      ellipsis:true,
      hideInSearch: true,
      width: 240,
      renderFormItem: (
        _,
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        { type, defaultRender, formItemProps, fieldProps, ...rest },
      ) => {
        return (
          // value 和 onchange 会通过 form 自动注入。
          <MdEditor
            // 组件的配置
            {...fieldProps}
          />
        );
      },
    },
    {
      title: '答案',
      dataIndex: 'answer',
      valueType: 'text',
      ellipsis:true,
      hideInSearch: true,
      width: 640,
      renderFormItem: (
        _,
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        { type, defaultRender, formItemProps, fieldProps, ...rest },
      ) => {
        return (
          // value 和 onchange 会通过 form 自动注入。
          <MdEditor
            // 组件的配置
            {...fieldProps}
          />
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'select',
      fieldProps: {
        mode: 'tags',
      },
      render: (_, record) => {
        const tagList = JSON.parse(record.tags || '[]');
        return <TagList tagList={tagList} />;
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.Question>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          defaultSelectedRowKeys: [],
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space size={16}>
              <Button
                onClick={() => {
                  setSelectQuestionIdList(selectedRowKeys as number[]);
                  setAddQuestionToBankBatchModalVisible(true);
                }}
              >
                批量添加到题库
              </Button>
              <Button
                onClick={() => {
                  setSelectQuestionIdList(selectedRowKeys as number[]);
                  setRemoveQuestionFromBankBatchModalVisible(true);
                }}
              >
                批量从题库删除题目
              </Button>
              <Popconfirm
                title="确认删除"
                description="是否确认删除题目?"
                onConfirm={() => {}}
                okText="确认"
                cancelText="取消"
              >
                <Button
                  danger
                  onClick={() => {
                    handleDeleteBatch(selectedRowKeys as number[]);
                  }}
                >
                  批量删除题目
                </Button>
              </Popconfirm>
            </Space>
          );
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-expect-error
          const { data, code } = await listQuestionUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.QuestionQueryDto);

          return {
            success: code === 20000,
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            data: data?.records || [],
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
      <AddBankBatchModal
        visible={addQuestionToBankBatchModalVisible}
        questionIdList={selectQuestionIdList}
        onSubmit={() => {
          setAddQuestionToBankBatchModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setAddQuestionToBankBatchModalVisible(false);
          actionRef.current?.reload();
        }}
      />
      <RemoveBankBatchModal
        visible={removeQuestionFromBankBatchModalVisible}
        questionIdList={selectQuestionIdList}
        onSubmit={() => {
          setRemoveQuestionFromBankBatchModalVisible(false);
        }}
        onCancel={() => {
          setRemoveQuestionFromBankBatchModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default QuestionAdminPage;
